package com.lanou.moving.volley;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;


//构造方法私有  防止其他类中通过new创建一个对象
//构造方法中添加一个拉取图片的功能


/**
 * Created by dllo on 15/9/17.
 */
public class VolleySingleton {
    private static VolleySingleton volleySingleton;
    private RequestQueue requestQueue;
    private Context context;
    private static final String TAG = "VolleySingleton";
    private ImageLoader imageLoader;

    // 构造方法私有,防止其他类中通过new创建对象

    private VolleySingleton(Context context) {
        this.context = context;
        requestQueue = getRequestQueue();
        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {

            LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(10 * 1024 * 1024);



                @Override
                public Bitmap getBitmap (String url){
                    return cache.get(url);
                }

                @Override
                public void putBitmap (String url, Bitmap bitmap){
                    cache.put(url, bitmap);
                }
            });
        }

        public ImageLoader getImageLoader () {
            return imageLoader;

        }

        // 提供一个静态方法,获取本类的实例
        public static VolleySingleton getInstance (Context context){
            if (volleySingleton == null) {
                volleySingleton = new VolleySingleton(context);
            }
            return volleySingleton;
        }


        private RequestQueue getRequestQueue () {
            if (requestQueue == null) {
                requestQueue = Volley.newRequestQueue(context);
            }
                return requestQueue;
            }


            //提供一个方法 将request添加到队列

            // 提供一个方法将Request添加到队列
            // T为泛型

    public <T> void addQueue(Request<T> request) {
        request.setTag(TAG);
        getRequestQueue().add(request);
    }


    //  自定义tag标签

    public <T> void addQueue(Request<T> request, String tag) {
        request.setTag(tag);
        getRequestQueue().add(request);
    }


    public void removeRequest(Object object) {
        getRequestQueue().cancelAll(object);
    }


}